package filmring

class UserController {

    def index = { }

    def signIn ={
        System.out.println("Attempting to sign in with username ${params.username} and password ${params.password}")
        FRUser user =FRUser.findByUsername(params.username)
        if(user != null){
            if(user.password==params.password){
                session.user=user.id
                session.signedIn=true
            }
        }
        redirect(controller: "movie" ,action: "index")
    }

    def create ={
        if(FRUser.findByEmail(params.email)==null && FRUser.findByUsername(params.email)==null){
            FRUser user = new FRUser(username:params.username, password: params.password, email:params.email)
            user.save()
            ActivityFeedEvent event = new ActivityFeedEvent(user:user, movie:null, action:"User account created on ${new Date().toTimestamp()}")
            event.save()
            System.out.println("Created user with username ${params.username} and password ${params.password}")
        } else{
            if(FRUser.findByEmail(params.email)!=null ){
                render(view:"create", msg:"You can only create one account for an email address.")
            }
            if(FRUser.findByUsername(params.username)!=null){
                render(view:"create", msg:"Someone is already using this username please choose a different one.")
            }
        }
        redirect(controller:"user",action:"signIn", params:[username:params.username, password:params.password])

    }

    def signUp ={
        render(view:"create", msg:"")
    }

    def signOut ={
        session.user=0
        session.signedIn=false
        redirect(controller:"movie", action:"index")
    }
}
